package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.system.domain.ProjectMessage;
import com.ecnu.system.domain.dto.MyMessageDTO;
import com.ecnu.system.domain.vo.ProjectMessageVO;
import com.ecnu.system.mapper.ProjectMessageMapper;
import com.ecnu.system.service.IProjectMessageService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

@Service
public class ProjectMessageServiceImpl extends ServiceImpl<ProjectMessageMapper, ProjectMessage> implements IProjectMessageService {

    @Autowired
    private ProjectMessageMapper projectMessageMapper;

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    @Override
    public TableDataInfo selectList(MyMessageDTO dto, LoginUser loginUser) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
//        List<ProjectMessageVO> messageVOS = projectMessageMapper.selectListForMyMessage(dto, loginUser.getUserId());
        LambdaQueryWrapper<ProjectMessage> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ProjectMessage::getType, dto.getType());//类型
        wrapper.eq(ProjectMessage::getStatus, dto.getStatus());//状态
        if (dto.getType().equals("1")) {//1消息情况带上创建人
            wrapper.eq(ProjectMessage::getCreateUser, loginUser.getUserId());//创建人
        }


        if (loginUser.getUser().getRoles().get(0).getRoleId() != 1L && loginUser.getUser().getRoles().get(0).getRoleId() != 2L) { //非管理员筛除
            wrapper.eq(ProjectMessage::getDeptId, loginUser.getDeptId());
        } else {
            wrapper.eq(ProjectMessage::getDeptId, "All");
        }
        wrapper.orderByDesc(ProjectMessage::getCreateTime);
        startPage(dto.getPageDomain());
        List<ProjectMessage> projectMessages = projectMessageMapper.selectList(wrapper);
        List<ProjectMessageVO> copy = OtherUtil.copy(projectMessages, ProjectMessageVO.class);

        copy.forEach(projectMessageVO -> {
            projectMessageVO.setPublisher("系统");
            projectMessageVO.setTitle(loginUser.getUser().getNickName() + "，" + projectMessageVO.getTitle());
        });

        return OtherUtil.tableSuccess2(copy, new PageInfo(projectMessages).getTotal());
    }
}
